package com.example.luke.shengdangxiaoattendance.Util;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.IOException;
import java.net.NetworkInterface;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Random;
import java.util.UUID;

//import net.sourceforge.pinyin4j.PinyinHelper;

/**
 * Created by yrdev on 7/18/16.
 */
public class GlobalFunction {
    public static ProgressDialog dialog;
    private static final String lanKey="lan_key";
    public static Context context;
    public static Context activity;


    public static void printText(String tag, String content){
        Log.d(tag,content);

    }

    public static void printTextByTag(String content){
        Log.d("tags",content);

    }

    public static void showProgress(Context context, String title, String body){
        if (GlobalFunction.dialog==null){
            GlobalFunction.dialog= ProgressDialog.show(context,title,body);

        }else {
            GlobalFunction.dialog.show();
        }
    }

    public static boolean checkJsonHead(JSONObject jsonObject) throws org.json.JSONException{
        boolean stat=false;
        String response = jsonObject.getString("response");
        GlobalFunction.printTextByTag(response);
        JSONObject respBody = new JSONObject(response);

        String headItem = respBody.getString("head");
        JSONObject head = new JSONObject(headItem);

        if (head.getString("respCode").equals("0000") && head.getString("respMsg").equals("ok")){
            stat=true;

        }

        return stat;

    }

    public static Date getDateFromDatePicker(DatePicker datePicker){
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year =  datePicker.getYear();

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);

        return calendar.getTime();
    }

    public static JSONObject getJsonBody(JSONObject jsonObject)throws org.json.JSONException{
        String response = jsonObject.getString("response");
        GlobalFunction.printTextByTag(response);
        JSONObject respBody = new JSONObject(response);

        String body = respBody.getString("body");

        return new JSONObject(body);

    }

    public static void showProgress(Context context, String body){

        try {

            if (GlobalFunction.dialog==null){
                //GlobalFunction.dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                GlobalFunction.dialog= ProgressDialog.show(context,"提示",body);


            }else {
                GlobalFunction.dialog.show();

            }


        }catch (Exception e){

            e.printStackTrace();
        }

    }


   public static String getMyUUID(Activity activity){
        final TelephonyManager tm = (TelephonyManager) activity.getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, tmPhone, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();

        androidId = "" + Settings.Secure.getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
        UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
        String uniqueId = deviceUuid.toString();
        Log.d("debug","uuid="+uniqueId);
        return uniqueId;
    }

    public static void  dismissProgress(){
        if (GlobalFunction.dialog!=null){
            GlobalFunction.dialog.dismiss();
            GlobalFunction.dialog=null;

        }
    }
    public static Integer convertToInt(Double value){
        String string=String.valueOf(value);
        //String str = string.substring(0, string.indexOf(".")) + string.substring(string.indexOf(".") + 1);
        //int intgeo = Integer.parseInt(str);
        double num;
        long iPart;
        double fPart;

// Get user input
        num = value;

        iPart = (long) num;
        fPart = num - iPart;

      String fractioNalPart=  String.valueOf(fPart).replace("0.","");

        GlobalFunction.printTextByTag(fractioNalPart);

        return (int)Double.parseDouble(string);





    }
    public static  boolean isVpnConnected() {
        try {
            Enumeration<NetworkInterface> niList = NetworkInterface.getNetworkInterfaces();
            if(niList != null) {
                for (NetworkInterface intf : Collections.list(niList)) {
                    if(!intf.isUp() || intf.getInterfaceAddresses().size() == 0) {
                        continue;
                    }
                    if ("tun0".equals(intf.getName()) || "ppp0".equals(intf.getName())){
                        return true;
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }


    public static boolean checkNetWorkStatus(Context context){

        boolean result;
        ConnectivityManager cm=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();
        if ( netinfo !=null && netinfo.isConnected() ) {
            result=true;

        }else{
            result=false;

        }
        return result;
    }

    public static boolean isTimeBetweenTwoTime(String argStartTime, String argEndTime) throws ParseException {
boolean stat=false;

        String reg = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
        //
        if (argStartTime.matches(reg) && argEndTime.matches(reg)) {
            boolean valid = false;
            // Start Time
            Date startTime = new SimpleDateFormat("HH:mm",Locale.getDefault())
                    .parse(argStartTime);
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startTime);

            // Current Time
            Date currentTime = new SimpleDateFormat("HH:mm",Locale.getDefault())
                    .parse(GlobalFunction.getCurrentHourMin());
            Calendar currentCalendar = Calendar.getInstance();
            currentCalendar.setTime(currentTime);

            // End Time
            Date endTime = new SimpleDateFormat("HH:mm",Locale.getDefault())
                    .parse(argEndTime);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endTime);

            //
            if (currentTime.compareTo(endTime) < 0) {

                currentCalendar.add(Calendar.DATE, 1);
                currentTime = currentCalendar.getTime();

            }

            if (startTime.compareTo(endTime) < 0) {

                startCalendar.add(Calendar.DATE, 1);
                startTime = startCalendar.getTime();

            }
            //
            if (currentTime.before(startTime)) {

                System.out.println(" Time is Lesser ");

                valid = false;
            } else {

                if (currentTime.after(endTime)) {
                    endCalendar.add(Calendar.DATE, 1);
                    endTime = endCalendar.getTime();

                }

                System.out.println("Comparing , Start Time /n " + startTime);
                System.out.println("Comparing , End Time /n " + endTime);
                System.out
                        .println("Comparing , Current Time /n " + currentTime);

                if (currentTime.before(endTime)) {
                    System.out.println("RESULT, Time lies b/w");
                    valid = true;
                } else {
                    valid = false;
                    System.out.println("RESULT, Time does not lies b/w");
                }

            }
            return valid;

        } else {
            throw new IllegalArgumentException(
                    "Not a valid time, expecting HH:MM:SS format");
        }



    }
    public  static long minDiff(Date date1,Date date2){
        long diff = date1.getTime() - date2.getTime();
        long seconds = diff / 1000;
        long minutes = seconds / 60;

        return  minutes;

    }
    public static long getHourMinDifference(Date starTime, Date endTime) {

        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = starTime;

            two = endTime;

            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);

            //GlobalFunction.printTextByTag(hour + "小时" + min + "分");

        } catch (Exception e) {

            e.printStackTrace();
        }
        return (hour*60)+min;



    }

    public  static String convertTo24HourFormat (String date){
        String[]dateTime=  date.split(" ");
        String[] dateSplitted=dateTime[0].split("-");

        Date temp=GlobalFunction.convertStrToDate(date,"YYYY-MM-dd hh:mm:ss");
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(temp);

        int hour=calendar.get(Calendar.HOUR);

        hour=hour+12;
        if (hour>24)
            hour=hour-24;

        String hourString="";
        if (hour<10)
            hourString="0"+hour;
        else
            hourString=hour+"";


        String minString="";
        if (calendar.get(Calendar.MINUTE)<10)
            minString="0"+calendar.get(Calendar.MINUTE);

        else
            minString=calendar.get(Calendar.MINUTE)+"";


        String secondString="";
        if (calendar.get(Calendar.SECOND)<10)
            secondString="0"+calendar.get(Calendar.SECOND);

        else
            secondString=calendar.get(Calendar.SECOND)+"";



        return  dateSplitted[0]+"-"+dateSplitted[1]+"-"+dateSplitted[2]+" "+hourString+":"+minString+":"+secondString;



    }


    public static Double convertToDouble(Integer value){


        return (double)value;


    }


    public static String getSerialNumber(){


        try {
            String serial = null;
            String android_id =  Settings.Secure.getString(context.getContentResolver(),
                    Settings.Secure.ANDROID_ID);



            return android_id.toUpperCase();
        }catch (Exception e){


            return  e.getMessage();

        }



    }
    public  static Date convertStrToDate(String date,String format){

        try {

            SimpleDateFormat formatter=new SimpleDateFormat(format, Locale.getDefault());
            return  formatter.parse(date);

        }catch (Exception e){



        }
        return  null;


    }

   public static boolean isNetworkAvailable() {

        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();


    }

    public static   void initLanguage(Context context){

        Locale myLocale= new Locale(GlobalFunction.getCurrentLanKey(context));
        Resources res=context.getResources();
        DisplayMetrics dm=res.getDisplayMetrics();
        Configuration configuration=res.getConfiguration();
        configuration.locale=myLocale;
        res.updateConfiguration(configuration,dm);


    }
    public static String getResourceString(Context context, int key){
        return context.getResources().getString(key);

    }


    public static String getCurrentLanKey(Context context){

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());

        return settings.getString(GlobalFunction.lanKey, Locale.getDefault().getLanguage());

    }

    public static void setLanKey(Context context, String key){

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());

        SharedPreferences.Editor editor = settings.edit();
        editor.putString(GlobalFunction.lanKey,key ).apply();

    }


    public static void showKeyboardForEditText(Context context, EditText editText){
        InputMethodManager imm = (InputMethodManager)context. getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
    public static int convertToInt(String value){
        return Integer.valueOf(value);

    }
    public static void ToastAlert(final Context context, final String alert){
      Handler  mHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message message) {
                Toast.makeText(context,alert, Toast.LENGTH_SHORT).show();

                // This is where you do your work in the UI thread.
                // Your worker tells you in the message what to do.
            }
        };
        Message message = mHandler.obtainMessage(0,alert);

        message.sendToTarget();


    }

    public  static  int converToPx(Context context, int dp){
    Resources r = context.getResources();
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
    return (int)px;

    }

    public  static String getCurrentDateTime(){

            DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.getDefault());
            Date date = new Date();
            return dateFormat.format(date);

    }


    public  static String convertDate(Date date,String format){

        DateFormat df = new SimpleDateFormat(format,Locale.getDefault());



        return df.format(date);



    }

    public  static String httpLatestReqTime(){

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }
    public static String checkedPriceText(Double price){

        return String.format(Locale.getDefault(),"%.2f",price);

    }
   public  static String goodRequestHttpTime(){

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }

    public  static String getTimeWithFomat(Date date,String format){

        DateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault());

        return dateFormat.format(date);

    }
    public  static String getCurrentDate(){

        DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }

    public  static String getCurrentTime(){

        DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }

    public  static String getCurrentHourMin(){

        DateFormat dateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
        Date date = new Date();
        return dateFormat.format(date);

    }

    public static String getOnlyID(Context context){

        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        String ts = String.valueOf( System.currentTimeMillis());


        return ts+tm.getDeviceId().substring(0,4);


    }
    public static String getUniqueId(){
        Random rand = new Random();


        StringBuilder stringBuilder=new StringBuilder();
        String ts = String.valueOf( System.currentTimeMillis());

        for (int i=0;i<=3;i++){
            int  n = rand.nextInt(9) + 1;
          stringBuilder.append(n+"");

        }

        return ts+ stringBuilder.toString();



    }
    private String convertToHexString(int x){

        System.out.println(x + "的十六进制结果是：" + Integer.toHexString(x));
        String hexString= Integer.toHexString(x);
        return hexString;

    }
    public static ArrayList<String> getConvertedName(String name){

        ArrayList<String>arrayList=new ArrayList<>();
        if (!arrayList.contains(name)){

            arrayList.add(name);
        }

        char[] tempArr=name.toCharArray();

        for (char splitted:tempArr){

            String[]converted= new String[]{};


            //PinyinHelper.toHanyuPinyinStringArray(splitted);

            if (converted!=null && converted[0].length()>0){

                if (!arrayList.contains(converted[0])){
                    arrayList.add(converted[0]);
                }
            }
        }



        return arrayList;

    }

    public static String getVersionCode(Context context){
        PackageManager packageManager=context.getPackageManager();
        PackageInfo packageInfo;
        String versionCode="";
        try {
            packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
            versionCode=packageInfo.versionCode+"";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;

    }

    public static String getVersionName(Context context){
        PackageManager packageManager=context.getPackageManager();
        PackageInfo packageInfo;
        String versionCode="";
        try {
            packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
            versionCode=packageInfo.versionName+"";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;

    }


    public static String getTime(){

        long time=  System.currentTimeMillis()/1000;//获取系统时间的10位的时间戳

        String  str=String.valueOf(time);

        return str;

    }

    public static Date getNextDay(){
        Date date = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, 1);
        //date = calendar.getTime();
        return calendar.getTime();

    }
//    public static ArrayList<String> getConvertedName(String name){
//
//        ArrayList<String> arrayList=new ArrayList<>();
//        if (!arrayList.contains(name)){
//
//            arrayList.add(name);
//        }
//
//        char[] tempArr=name.toCharArray();
//
//        for (char splitted:tempArr){
//
//            String[]converted= PinyinHelper.toHanyuPinyinStringArray(splitted);
//
//            if (converted!=null && converted[0].length()>0){
//
//                if (!arrayList.contains(converted[0])){
//                    arrayList.add(converted[0]);
//                }
//            }
//        }
//
//
//
//        return arrayList;
//
//    }

    public  static void playMusicFile(Context context,String file){
        try {
            int resID=context.getResources().getIdentifier(file, "raw", context. getPackageName());
            MediaPlayer mediaPlayer=MediaPlayer.create(context,resID);

            mediaPlayer.start();

        }catch (Exception e){

            e.printStackTrace();
        }



    }
public static String getWeekDay(){

    String temp="";
    int dayOfWeek=Calendar.getInstance().get(Calendar.DAY_OF_WEEK);

    if (dayOfWeek==Calendar.MONDAY){
        temp="星期一";
    }
    else if (dayOfWeek==Calendar.TUESDAY){
        temp="星期二";
    }

    else if (dayOfWeek==Calendar.WEDNESDAY){
        temp="星期三";
    }
    else if (dayOfWeek==Calendar.THURSDAY){

        temp="星期四";

    }
    else if (dayOfWeek==Calendar.FRIDAY){

        temp="星期五";
    }
    else if (dayOfWeek==Calendar.SATURDAY){

        temp="星期六";

    }else {
        temp="星期日";
    }
    return temp;



    }

}
